import md5
import urllib
import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.api import urlfetch
from google.appengine.ext import db
from google.appengine.api import images

from Img import Img
import utils.imageutils as imageutils
from Img import NotSupportedImageEncodingError

import logging

class resizeimg(webapp.RequestHandler):
    def get(self):
        #request.path_qs      #/resize/http%3A//www.sgei.com%252Ffjalg.asp%253Ffjao%253Dtwr?ffff=7
        imgurl = self.request.path_qs[len('/resize/'):]
        width, imgurl = imgurl.split('/', 1)
        height, imgurl = imgurl.split('/', 1)
        width = int(width)
        height = int(height)
        imgurl = urllib.unquote_plus(imgurl)
        #self.response.out.write(self.request.url)
        #self.response.out.write(imgurl)
        #return
        heads = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT)',
                 'referer' : webapp.Request.blank(imgurl).host_url}
        #self.response.out.write(imgurl)
        #self.response.out.flush()
        resp = urlfetch.fetch(imgurl,
               method=urlfetch.GET,
               headers=heads)
        #self.response.out.write('\n--------------------------------\n')
        #self.response.out.write('\n'.join([k + ':' + resp.headers[k] for k in resp.headers.keys()]))
        #self.response.out.write('\n--------------------------------\n')
        #self.response.out.write(resp.content)

        #self.response.headers['content-type'] = resp.headers['content-type']
        #self.response.out.write('\n'.join([k + ':' + resp.headers[k] for k in resp.headers.keys()]))

        if resp.status_code == 200:
            content_type = resp.headers.get('Content-Type')
            if content_type and content_type.split('/')[0].lower() == 'image':
                imgEncoding = content_type.split('/')[1].upper()
                if Img.isSupported(imgEncoding):
                    #get thumbnail first
                    try:
                        img = images.Image(resp.content)
                        img.resize(width=width, height=height)
                        img.im_feeling_lucky()
                        thumbnail = img.execute_transforms(output_encoding=images.JPEG)
                        
                        self.response.headers['Content-Type'] = 'image/jpeg'
                        self.response.out.write(thumbnail)
                        return
                    except NotSupportedImageEncodingError:
                        #not supported encoding
                        self.redirect('/error/' + 'The url [' + imgurl + '] is not a supported encoding image')
                        return
                    return
                else:
                    #not supported encoding
                    self.redirect('/error/' + 'The url [' + imgurl + '] is not a supported encoding image')
                    return
            else:
                #not a image
                self.redirect('/error/' + 'The url [' + imgurl + '] is not a image')
                return
        else:
            #fetch error
            self.redirect('/error/' + 'error occor while fetching url [' + imgurl + ']')
            return
    

def main():
    application = webapp.WSGIApplication(
                           [('/resize/.*', resizeimg)],
                           debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()

